%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Module summary
%%
%% Test case for mysql queries
%%
%% Input parameters;
%% 
%% [Hostname,
%%  Queries,             default: 1000
%%  String_length,       default: 10
%%  mixed | puts | gets  default: mixed
%%  ]
%%
%%%%%%%%%%%%%%%%%%%%%%%
-module(test_mysql).
-export([setup/1,test/1,tear_down/1]).

-behaviour(testcase).

-record(state, {v1,         % v1 & v1; the values used
                v2,         % when performing queries
                type        % mixed | puts | gets               
                }).

setup(Params) ->
    % Read parameters. Doesn't do any type checking, write correct! :)
    % TODO only host as parameter?
    {Host,Queries,StrLn,Type} = read_params(Params),
    
    % Setup connection
    mysql_lib:start(Host),

    % Fulkod! (tömma mysql tabeller innan test)
    mysql_lib ! {fetch, "truncate table apa", self()},
    receive 
        {reply, Reply} -> Reply
    end,   

    % Setup queries
    Values = test_lib:random_key_value_pairs(Queries,StrLn),
    {Values1,Values2} = lists:split(length(Values) div 2, Values),

    #state{v1 = Values1, v2 = Values2, type = Type}.

test(State) ->
    FirstTimestamp = os:timestamp(),

    % Perform queries
    case State#state.type of
        mixed -> mysql_lib:put_list(State#state.v1),
                 mysql_lib:get_list(State#state.v1);
        puts  -> mysql_lib:put_list(State#state.v1),
                 mysql_lib:put_list(State#state.v2);
        gets  -> mysql_lib:get_list(State#state.v1),
                 mysql_lib:get_list(State#state.v2)
    end,

    SecondTimeStamp = os:timestamp(),

    % Return the timestamp difference of the queries
    [{slave, node()},
     {queries, length(State#state.v1) + length(State#state.v2)},
     {time,time_stamp_diff(FirstTimestamp,SecondTimeStamp)}].

tear_down(_State) ->
    % Close socket connection
    mysql_lib:stop().

read_params(Params) ->
    case length(Params) of
        0 -> {"localhost",1000,10,mixed};
        1 -> Host = lists:nth(1,Params),
             {Host,1000,10,mixed};
        2 -> Host = lists:nth(1,Params),
             Queries = lists:nth(2,Params),
             {Host,Queries,10,mixed};
        3 -> Host = lists:nth(1,Params),
             Queries = lists:nth(2,Params),
             StrLn = lists:nth(3,Params),
             {Host,Queries,StrLn,mixed};
        4 -> Host = lists:nth(1,Params),
             Queries = lists:nth(2,Params),
             StrLn = lists:nth(3,Params),
             Type = lists:nth(4,Params),
             {Host,Queries,StrLn,Type};
        _ -> error("test_mysql: wrong number of arguments.\n")
    end.


% Borrowing Kristian's code
time_stamp_diff(Time1,Time2) ->
   {A,B,C} = Time1,
   {D,E,F} = Time2,
   {_,H,I} = {D-A,E-B,F-C},
   %% H * 1000, G * 1 billion
   H + (I / 1000000).
